import json
import re
from loguru import logger

class OpenSSLStore:
    def __init__(self, gen_funs_json_path=""):
        self.generated_functions = self.read_json_gen_funs(gen_funs_json_path)
        self.concurrent_functions = []
        self.thread_safety_term = ["thread", "lock", "once", "reference", "atom"]
        self.cert_key_term = ["cert", "private key", "public key", "X509",]
        self.certs_path="certs/"

    def read_json_gen_funs(self, path):
        try:
            with open(path, "r") as f:
                return json.load(f)
        except FileNotFoundError:
            logger.error(f"json.load() failed：文件 '{path}' 不存在！")
            return []
        except json.JSONDecodeError:
            logger.error(f"json.load() failed：文件 '{path}' 不是有效的JSON格式！")
            return []

    def write_json_gen_funs(self, path):    
        try:
            with open(path, "w") as f:
                json.dump(self.generated_functions, f, indent=4)
        except FileNotFoundError:
            logger.error(f"json.dump() failed：文件 '{path}' 不存在！")
            return None
        except json.JSONDecodeError:
            logger.error(f"json.dump() failed：文件 '{path}' 不是有效的JSON格式！")
            return None
    
    def get_generated_functions(self):
        return self.generated_functions
    
    def check_thread_safety(self, fun: str, content: str):
        if fun in self.concurrent_functions:
            return True
        
        for term in self.thread_safety_term:
            if re.search(term, content, re.IGNORECASE):
                return True
            
        return False
    
    def check_cert_key(self, content: str):
        for term in self.cert_key_term:
            if re.search(term, content, re.IGNORECASE):
                return True
            
        return False

    def set_certs_path(self, path: str):
        logger.info(f"certificate path: {path}")
        self.certs_path = path
    
    def get_certs_path(self):
        return self.certs_path